<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="体检人员ID" prop="personId">
        <el-input v-model="queryParams.personId" placeholder="请输入体检人员ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="采集时间" prop="collectionTime">
        <el-date-picker clearable v-model="queryParams.collectionTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择采集时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="采集地点" prop="collectionPlace">
        <el-input v-model="queryParams.collectionPlace" placeholder="请输入采集地点" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="样本条码" prop="barcode">
        <el-input v-model="queryParams.barcode" placeholder="请输入样本条码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['health:collection:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['health:collection:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['health:collection:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['health:collection:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="collectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="样本 ID" align="center" prop="sampleId" />
      <el-table-column label="体检人员ID" align="center" prop="personId" />
      <el-table-column label="样本类型" align="center">
        <template #default="scope">
          {{ itemIdToName[scope.row.sampleType] || '未知样本类型' }}
        </template>
      </el-table-column>
      <el-table-column label="采集时间" align="center" prop="collectionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.collectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采集地点" align="center" prop="collectionPlace" />
      <el-table-column label="样本条码" align="center" prop="barcode" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          {{ scope.row.status === 0 ? '未检查' : (scope.row.status === 1 ? '已检查' : '未知状态') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['health:collection:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['health:collection:remove']">删除</el-button>
          <el-button link type="primary" @click="handleCollection(scope.row)"
            v-hasPermi="['health:collection:edit']">检查</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改样本采集对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="collectionRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="体检人员ID" prop="personId">
          <el-input v-model="form.personId" placeholder="请输入体检人员ID" />
        </el-form-item> -->
        <el-form-item label="采集时间" prop="collectionTime">
          <el-date-picker clearable v-model="form.collectionTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择采集时间" disabled>
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="采集地点" prop="collectionPlace">
          <el-input v-model="form.collectionPlace" placeholder="请输入采集地点" />
        </el-form-item>
        <el-form-item label="样本条码" prop="barcode">
          <el-input v-model="form.barcode" placeholder="请输入样本条码" />
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Collection">
import { listCollection, getCollection, delCollection, addCollection, updateCollection } from "@/api/health/collection"
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/health/item"


const { proxy } = getCurrentInstance()

const collectionList = ref([])
const itemList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sampleId: null,
    personId: null,
    sampleType: null,
    collectionTime: null,
    collectionPlace: null,
    barcode: null,
    status: null
  },
  itemsNames: {
     pageNum: 1,
    pageSize: 100,
    itemId: null,
    itemName: null,
    itemStaue: null,
    price: null,
    normalRange: null,
  },
  rules: {
  }
})

const { queryParams, itemsNames, form, rules } = toRefs(data)

const itemIdToName = computed(() => {
  return itemList.value.reduce((acc, item) => {
    acc[item.itemId] = item.itemName;
    return acc;
  }, {});
});

// const sampleTypeOptions = {
//   1: '血常规',
//   2: '尿常规',
//   3: '肝功能全套',
//   4: '肾功能三项',
//   5: '血脂四项',
//   6: '心电图',
//   7: '胸部X光',
//   8: '腹部B超',
//   9: '甲状腺功能三项',
//   10: '癌胚抗原(CEA)',
//   11: '采血',
//   12: '采便'
// };

/** 查询样本采集列表 */
function getList() {
  loading.value = true
  listCollection(queryParams.value).then(response => {
    collectionList.value = response.rows
    total.value = response.total
    loading.value = false
  });
  listItem(itemsNames.value).then(response => {
    itemList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sampleId: null,
    personId: null,
    sampleType: null,
    collectionTime: null,
    collectionPlace: null,
    barcode: null,
    status: null
  }
  proxy.resetForm("collectionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加样本采集"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  updateCollection(_id,).then(response => {
    open.value = true
    title.value = "修改样本采集"
  })
}
/** 采集按钮操作 */
function handleCollection(row) {
  const _id = row.id || ids.value;
  getCollection(_id).then(response => {
    form.value = response.data;
    form.value.collectionTime = new Date().toISOString().slice(0, 10); // 设置采集时间为当前日期
    form.value.status = '1'; // 修改状态为 1
    open.value = true;
    title.value = "修改样本采集";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["collectionRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCollection(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCollection(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除样本采集编号为"' + _ids + '"的数据项？').then(function () {
    return delCollection(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('health/collection/export', {
    ...queryParams.value
  }, `collection_${new Date().getTime()}.xlsx`)
}

getList()
</script>
